package com.atguigu.yygh.user.service.impl;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.PatientService;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2021-12-15
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Autowired
    private PatientService patientService;

    @Override
    public void approval(Long userId, Integer anthStatus) {
        if (anthStatus.intValue()==-1 || anthStatus.intValue()==2){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(anthStatus);
            baseMapper.updateById(userInfo);
        }
    }

    @Override
    public Map<String, Object> showUserInfo(Long userId) {
/*        Map<String, Object> map = new HashMap<>();
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(id));
        List<Patient> patientList = patientService.findAll(id);

        map.put("userInfo",userInfo);
        map.put("patientList",patientList);
        return map;*/
        Map<String,Object> map = new HashMap<>();
        //根据userid查询用户基本信息
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(userId));

        //根据用户id查询用户下面就诊人数据
        List<Patient> patientList = patientService.findAll(userId);

        map.put("userInfo",userInfo);
        map.put("patientList",patientList);
        return map;
    }

    @Override
    public void lock(Long userId, Integer status) {
        if (status.intValue()==0 || status.intValue()==1){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }

    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        String keyword = userInfoQueryVo.getKeyword();
        Integer status = userInfoQueryVo.getStatus();
        Integer authStatus = userInfoQueryVo.getAuthStatus();
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();

        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(keyword)) {
            wrapper.like("name",keyword);
        }
        if(!StringUtils.isEmpty(status)) {
            wrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)) {
            wrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        Page<UserInfo> userInfoPage = baseMapper.selectPage(pageParam, wrapper);
        userInfoPage.getRecords().stream().forEach(item->{
            this.packageUserInfo(item);
        });
        
        return userInfoPage;
    }

    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        UserInfo userInfo = baseMapper.selectById(userId);
        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());

        baseMapper.updateById(userInfo);
    }

    //用户登录
    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        //得到登录数据
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();

        //判断数据是否为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException(20001, "登录数据为空");
        }
        //// TODO: 2021/12/15 校验验证码
        // redis校验验证码
        String codeRedis = redisTemplate.opsForValue().get(phone);
        if (!code.equals(codeRedis)) {
            throw new YyghException(20001, "验证校验码失败");
        }
        //******获取
        String openid = loginVo.getOpenid();
        if (StringUtils.isEmpty(openid)) {
            //验证手机号是否已存在
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("phone", phone);
            UserInfo userInfo = baseMapper.selectOne(wrapper);
            if (userInfo == null) {
                userInfo = new UserInfo();
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
            //校验是否被禁用
            if (userInfo.getStatus() == 0) {
                throw new YyghException(20001, "账号已被禁用");
            }
            //登录成功后返回数据
            Map<String, Object> map = get(userInfo);
            return map;
        } else {
            //1 根据绑定手机号查询数据库，是否存在和绑定手机号相同数据
            QueryWrapper<UserInfo> wrapperPhone = new QueryWrapper<>();
            wrapperPhone.eq("phone",phone);
            UserInfo userInfoPhone = baseMapper.selectOne(wrapperPhone);

            //2 数据库不存在和绑定手机号，直接更新微信数据手机号
            if(userInfoPhone == null) {
                //根据openid查询
                QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
                wrapper.eq("openid",openid);
                UserInfo userInfoWx = baseMapper.selectOne(wrapper);

                //设置绑定手机号
                userInfoWx.setPhone(phone);

                //更新
                baseMapper.updateById(userInfoWx);

                //6 登录成功之后，返回需要数据
                Map<String,Object> map = get(userInfoWx);
                return map;
            } else {
                //3 数据库存在相同绑定手机号
                //3.1 把存在手机号数据获取出来
                //userInfoPhone不为空
                //3.2 设置到微信数据中
                //根据openid查询
                QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
                wrapper.eq("openid",openid);
                UserInfo userInfoWx = baseMapper.selectOne(wrapper);

                //设置绑定手机号
                userInfoWx.setPhone(userInfoPhone.getPhone());
                //用户真实姓名
                userInfoWx.setName(userInfoPhone.getName());
                userInfoWx.setCertificatesType(userInfoPhone.getCertificatesType());
                userInfoWx.setCertificatesNo(userInfoPhone.getCertificatesNo());
                userInfoWx.setCertificatesUrl(userInfoPhone.getCertificatesUrl());

                //3.3 把手机号数据删除
                //baseMapper.deleteById(userInfoPhone.getId());
                QueryWrapper<UserInfo> wrapperDelete = new QueryWrapper<>();
                wrapperDelete.eq("phone",userInfoPhone.getPhone());
                baseMapper.delete(wrapperDelete);

                //3.4完成微信数据更新
                baseMapper.updateById(userInfoWx);

                //6 登录成功之后，返回需要数据
                Map<String,Object> map = get(userInfoWx);
                return map;
            }
        }
    }


    private Map<String, Object> get(UserInfo userInfo) {
        //返回页面显示名称
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        //根据userid和name生成token字符串
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        return map;
    }

    //编号对应名称
    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue()==0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }
}
